from fastapi import APIRouter, Depends, HTTPException, Request, Body
from typing import List, Dict, Any, Optional
import os
import json
from datetime import datetime
import uuid
from .auth import get_current_active_user, User

router = APIRouter(
    prefix="/api/process",
    tags=["流程管理"],
    responses={404: {"description": "Not found"}},
)

# 临时存储流程数据的目录
PROCESS_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "processes")
os.makedirs(PROCESS_DIR, exist_ok=True)

class Process:
    def __init__(self, id: str, name: str, description: str, flow_data: Dict, created_by: str, created_at: datetime):
        self.id = id
        self.name = name
        self.description = description
        self.flow_data = flow_data
        self.created_by = created_by
        self.created_at = created_at
        self.updated_at = created_at
        self.status = "active"

    def to_dict(self):
        return {
            "id": self.id,
            "name": self.name,
            "description": self.description,
            "flow_data": self.flow_data,
            "created_by": self.created_by,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
            "status": self.status
        }

    @classmethod
    def from_dict(cls, data):
        process = cls(
            id=data["id"],
            name=data["name"],
            description=data["description"],
            flow_data=data["flow_data"],
            created_by=data["created_by"],
            created_at=datetime.fromisoformat(data["created_at"])
        )
        process.updated_at = datetime.fromisoformat(data["updated_at"])
        process.status = data["status"]
        return process

def get_process_path(process_id: str) -> str:
    return os.path.join(PROCESS_DIR, f"{process_id}.json")

def save_process(process: Process) -> None:
    with open(get_process_path(process.id), "w", encoding="utf-8") as f:
        json.dump(process.to_dict(), f, ensure_ascii=False, indent=2)

def get_process(process_id: str) -> Optional[Process]:
    path = get_process_path(process_id)
    if not os.path.exists(path):
        return None
    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    return Process.from_dict(data)

def get_all_processes() -> List[Process]:
    processes = []
    for filename in os.listdir(PROCESS_DIR):
        if filename.endswith(".json"):
            with open(os.path.join(PROCESS_DIR, filename), "r", encoding="utf-8") as f:
                data = json.load(f)
                processes.append(Process.from_dict(data))
    return processes

def delete_process(process_id: str) -> bool:
    path = get_process_path(process_id)
    if os.path.exists(path):
        os.remove(path)
        return True
    return False

@router.get("/list", response_model=List[Dict])
async def list_processes(current_user: User = Depends(get_current_active_user)):
    processes = get_all_processes()
    return [p.to_dict() for p in processes]

@router.post("/create", response_model=Dict)
async def create_process(
    request: Request,
    current_user: User = Depends(get_current_active_user)
):
    data = await request.json()
    process_id = str(uuid.uuid4())
    process = Process(
        id=process_id,
        name=data.get("name", "新建流程"),
        description=data.get("description", ""),
        flow_data=data.get("flow_data", {}),
        created_by=current_user.username,
        created_at=datetime.now()
    )
    save_process(process)
    return process.to_dict()

@router.get("/{process_id}", response_model=Dict)
async def get_process_details(
    process_id: str,
    current_user: User = Depends(get_current_active_user)
):
    process = get_process(process_id)
    if not process:
        raise HTTPException(status_code=404, detail="流程不存在")
    return process.to_dict()

@router.put("/{process_id}", response_model=Dict)
async def update_process(
    process_id: str,
    request: Request,
    current_user: User = Depends(get_current_active_user)
):
    process = get_process(process_id)
    if not process:
        raise HTTPException(status_code=404, detail="流程不存在")
    
    data = await request.json()
    process.name = data.get("name", process.name)
    process.description = data.get("description", process.description)
    process.flow_data = data.get("flow_data", process.flow_data)
    process.updated_at = datetime.now()
    
    save_process(process)
    return process.to_dict()

@router.delete("/{process_id}")
async def remove_process(
    process_id: str,
    current_user: User = Depends(get_current_active_user)
):
    if delete_process(process_id):
        return {"message": "流程已删除"}
    raise HTTPException(status_code=404, detail="流程不存在")

@router.post("/{process_id}/run")
async def run_process(
    process_id: str,
    current_user: User = Depends(get_current_active_user)
):
    process = get_process(process_id)
    if not process:
        raise HTTPException(status_code=404, detail="流程不存在")
    
    # 这里只是一个示例，实际应该调用RPA执行引擎
    return {
        "message": f"流程 {process.name} 开始运行",
        "run_id": str(uuid.uuid4()),
        "status": "running"
    } 